﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Runtime.InteropServices;
using System.Data.SqlClient;
using System.Threading;

using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataManagementTools;
using ESRI.ArcGIS.Geometry;

namespace Tayninh2011
{
    public sealed partial class FrmCalculateLandPrize : Form
    {
        //dam bao form singleton
        private static bool isShown = false;
        private static readonly FrmCalculateLandPrize frmCalculateLandPrize = new FrmCalculateLandPrize();

        private string[,] arrUserInfo;
        private SqlConnection _sqlConnection = null;
        private string _strDatabase = "";
        private string _strServer = "";
        private string _strUser = "";
        private string _strPass = "";
        private string _sdeEnvironment="";
        private string _strPathTempFolder = "";     
        private string _strNameTempMdbFile = "";
        private TabControl _tabTayNinh;
        private TabControl _tabTanBien;
        private List<TabControl> _tabControlList = new List<TabControl>();

        private IWorkspaceEdit _sdeWorkspace;
        private IFeatureWorkspace _featureWorkspace;
        private static string _strNameTableThua = "tn_thua";
        private static string _strNameTableDuong = "tn_duong";
        private static string _strNameTableHem = "tn_hem";
        private string _strTinhHuyen = "";
        private string _strTinhXa = "";
        private string _strXemHuyen = "";
        private string _strXemXa = "";

        private string[] _strTenHuyen = new String[] { "TX Tây Ninh", "Tân Biên", "Tân Châu", "Dương Minh Châu", "Châu Thành", "Hòa Thành", "Bến Cầu", "Gò Dầu", "Trảng Bàng" };
        private string[] _strTenXaTayNinh = new String[] { "Phường 1", "Phường 2", "Phường 3", "Phường 4", "Phường Hiệp Ninh","Thạnh Tân","Tân Bình","Ninh Sơn","Bình Minh","Ninh Thạnh" };
        private string[] _strTenXaTanBien = new String[]{"TT Tân Biên","Tân Lập","Thạnh Tây", "Trà Vong","Mỏ Công","Tân Phong","Thạnh Bình","Tân Bình","Hòa Hiệp","Thạnh Bắc"};
        private string[] _strTenXaTanChau = new String[] {"TT Tân Châu","Thạnh Đông","Tân Hưng","Tân Hiệp","Tân Hội","Suối Dây","Tân Phú","Tân Đông","Tân Hà","Suối Ngô","Tân Hòa","Tân Thành" };
        private string[] _strTenXaDuongMinhChau = new String[] {"TT Dương Minh Châu","Bàu Năng","Suối Đá","Lộc Ninh","Cầu Khởi","Phan","Chà Là","Truông Mít","Bến Củi","Phước Minh","Phước Ninh" };
        private string[] _strTenXaChauThanh = new String[] { "TT Thanh Điền", "Thanh Điền", "Hảo Đước", "Trí Bình", "An Bình", "An Cơ", "Đồng Khởi", "Thái Bình", "Long Vĩnh", "Biên Giới", "Hòa Thạnh", "Hòa Hội", "Ninh Điền", "Phước Vinh", "Thành Long" };

        private Dictionary<string, string> _dicIdXa = new Dictionary<string, string>();

        private string[] _arrTenXaTemp;
        private string[][] _strTenXa;

        private TabControl currentSelectedTabControl=null;
        private string strCurrentSelectedTabPageName = "";

        private TnCalculatorFactory calcFactory;
        private TnToolsCalculator calcTool;

        public SqlConnection SqlConnection
        {
            get { return _sqlConnection; }
            set { _sqlConnection = value; }
        }

        public Dictionary<string, string> DicIdXa
        {
            get { return _dicIdXa; }
            set { _dicIdXa = value; }
        }

        public string StrPathTempFolder
        {
            get { return _strPathTempFolder; }
            set { _strPathTempFolder = value; }
        }
        public string StrNameTempMdbFile
        {
            get { return _strNameTempMdbFile; }
            set { _strNameTempMdbFile = value; }
        }
        public string SdeEnvironment
        {
            get { return _sdeEnvironment; }
            set { _sdeEnvironment = value; }
        }

        public IFeatureWorkspace FeatureWorkspace
        {
            get { return _featureWorkspace; }
            set { _featureWorkspace = value; }
        }

        public IWorkspaceEdit SdeWorkspace
        {
            get { return _sdeWorkspace; }
            set { _sdeWorkspace = value; }
        }

        public string StrDatabase
        {
            get { return _strDatabase; }
            set { _strDatabase = value; }
        }
        public void SetUserInfo(string[,] info)
        {
            this.arrUserInfo = info;
            this._strServer = info[0, 1];
            this._strDatabase = info[1, 1];
            this._strUser = info[2, 1];
            this._strPass = info[3, 1];
        }

        //Constructor
        private FrmCalculateLandPrize()
        {
            InitializeComponent();
            initTabControls();
            initDataOfCombobox();
            addButton();
            sbtnCalculate.contextMenuStrip.Items.Clear();
            //splitButton2.contextMenuStrip.Items.Add("hihi");
            sbtnCalculate.Colection = new string[] { "Tính lại toàn bộ", "Tính cho thửa chọn" };
            for (int i=0;i<sbtnCalculate.contextMenuStrip.Items.Count;i++)
            {
                sbtnCalculate.contextMenuStrip.Items[i].Click+=new EventHandler(showName);
            }
            sbtnCalculate.Text = sbtnCalculate.contextMenuStrip.Items[0].ToString();
            //_tabTayNinh.SelectedIndex = -1;
            //splitButton2.Colection=new string[]{"Tính lại toàn bộ","Tính cho thửa chọn"};
            //cbxTypeOfTableView.SelectedIndex = 0 ;

            
            
        }
        private void showName(object sender, EventArgs e)
        {
            sbtnCalculate.Text = sender.ToString();

            
        }

        public static FrmCalculateLandPrize FormCalculateLandPrize
        {
            get { return frmCalculateLandPrize; }
        }
        public new void Show()
        {
            if (isShown)
            {
                base.Show();
                base.Focus();
                base.WindowState = FormWindowState.Maximized;
                
            }
            else
            {
                base.Show();
                base.Focus();
                base.WindowState = FormWindowState.Maximized;
                isShown = true;
            }
        }

        private void initDataOfCombobox()
        {
            cbxTypeOfTableView.Items.Add("Toàn bộ thửa đã tính");
            cbxTypeOfTableView.Items.Add("Các thửa có 1 cách tính");
            cbxTypeOfTableView.Items.Add("Các thửa có nhiều cách tính");
            //addDataForCmbXa();
            addDataForCmbHuyen();
            
            
        }

        private void addDataForCmbHuyen()
        {
            //if (tbxHuyen.Text != "")
            //{
                try
                {
                    //string strNameTable="HUYEN";
                    //string strNameFields="";
                    //string strDieukien="";
                    //IFeatureClass featureClass = this.FeatureWorkspace.OpenFeatureClass(strNameTable);
                    //ICursor cursor = queryAttribute(strNameTable,strNameFields,strDieukien);
                    //IRow row=null;
                    cbxTypeCalHuyen.Items.Add("Tất cả các Huyện");
                    for (int i = 0; i < _strTenHuyen.Length; i++)
                    {
                        cbxTypeCalHuyen.Items.Add(_strTenHuyen[i]);
                    }
                    //while ((row = cursor.NextRow()) != null)
                    //{
                    //    cbxTypeCalXa.Items.Add(row.get_Value(0).ToString());
                    //}

                }
                catch (Exception err)
                {
                    cbxTypeCalHuyen.Items.Add("Không có lớp huyện");
                }
                finally
                {
                    cbxTypeCalHuyen.SelectedIndex = 0;
                }
            //}
        }

        private void addDataForCmbXa()
        {
            //if (tbxXa.Text != "")
            //{
            try
            {
                    //IFeatureDataset featureDataset = FeatureWorkspace.OpenFeatureDataset("phuong2");
                    
                    //string strNameTable="XA";
                    //string strNameFields="";
                    //string strDieukien="";
                    //IFeatureClass featureClass = this.FeatureWorkspace.OpenFeatureClass(strNameTable);
                    //ICursor cursor = queryAttribute(strNameTable,strNameFields,strDieukien);
                    //IRow row=null;
                //cbxTypeCalXa.Items.Add("Tất cả các Xã");
                cbxTypeCalXa.Items.Add("Tất cả các Xã");
                    //while ((row = cursor.NextRow()) != null)
                    //{
                    //    cbxTypeCalXa.Items.Add(row.get_Value(0).ToString());
                    //}

            }
            catch (Exception err)
            {
                cbxTypeCalXa.Items.Add("Không có lớp Xã");
            }
            finally
            {
                cbxTypeCalXa.SelectedIndex = 0;
            }
            //}
        }
        public void SetDatabase(string database)
        {
            this.lblDatabase.Text = StrDatabase;
        }
        public void SetWorkspace(IWorkspaceEdit workspace)
        {
            this.SdeWorkspace = workspace;
            this.FeatureWorkspace = (IFeatureWorkspace)this.SdeWorkspace;
            //MessageBox.Show(this.Workspace.ToString());
        }

        private void btnTinh_Click(object sender, EventArgs e)
        {
            //cbxTypeOfTableView_SelectedIndexChanged(null,new EventArgs());
            FrmMain frmMain = FrmMain.frmMain;
            frmMain = (FrmMain)this.MdiParent;
            //String n = 
            IDataset dataSet = (IDataset)SdeWorkspace;
            _strTinhHuyen = cbxTypeCalHuyen.Text;
            _strTinhXa = cbxTypeCalXa.Text;
            _strXemHuyen = cbxHuyenView.Text;
            this.backgroundWorker2.RunWorkerAsync();
            //ITnToolsSpatial toolSpatial = new TnTools();
            //ITnToolsTable toolTable = new TnTools();
            //ITnToolsCalculator toolCal = new TnTools();
            //IFeatureLayer fl = new FeatureLayerClass();
            //toolTable.TnFormatTable(SdeWorkspace,_strNameTableThua,_strNameTableDuong,_strNameTableHem);
            //try
            //{
            //    IFeatureClass fc = FeatureWorkspace.OpenFeatureClass("tn_duong_buff_05");
            //}
            //catch
            //{
            //    toolSpatial.TnBufferInsideSde(_strNameTableDuong, "tn_duong_buff_05", 0.5, SdeEnvironment, SdeWorkspace);
            //}
            //try
            //{
            //    IFeatureClass fc = FeatureWorkspace.OpenFeatureClass("tn_duong_buff_50");
            //}
            //catch
            //{
            //    toolSpatial.TnBufferInsideSde(_strNameTableDuong, "tn_duong_buff_50", 50, SdeEnvironment, SdeWorkspace);
            //}

            //fl = toolCal.TnTinhThuaMattien(_strNameTableThua, "tn_duong_buff_05", SdeWorkspace);
            //IFeatureClass flData = fl.FeatureClass;
            //ITable table = (ITable)flData;
            //System.Windows.Forms.Control.ControlCollection controlCol = _tabTayNinh.SelectedTab.Controls;
            //    DataGridView dtgv = new DataGridView();
            //    foreach (Control con in controlCol)
            //    {
            //        dtgv = (DataGridView)con;
            //    }
            //    toolTable.TnShowData(SdeWorkspace, dtgv, flData, "soto,sothua,loaidat,tenchu,diachi,kdat,giadat,dongia,somattien,socachtinh,ghichu", "",0);
            //MessageBox.Show(SdeWorkspace.PathName);
            //showDataThua(cbxTypeOfTableView.SelectedIndex);
            
            //HCalculateLandPrize hCalculateLandPrize = new HCalculateLandPrize(SdeWorkspace, _strNameTableThua, _strNameTableDuong, _strNameTableHem);
            //IFeatureClass duongBuffer50 = hCalculateLandPrize.Buffer(hCalculateLandPrize.GetFeatureClass(hCalculateLandPrize.StrNameTableDuong), 50, "FULL", "FLAT");
            //MessageBox.Show(duongBuffer50.Fields.FieldCount.ToString());
            //MessageBox.Show(frmMain.Workspace.ToString());
        }

        private void cbxTypeOfTableView_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            
        }
        private ICursor queryAttribute(string table,string fields, string dieukien)
        {
            IQueryFilter queryFilter = new QueryFilterClass();
            IQueryDef queryDef = FeatureWorkspace.CreateQueryDef();
            
            //cac truong tra ve
            //queryFilter.SubFields="SO_THUA, TENCHU";
            queryDef.Tables = table;
            queryDef.SubFields = "SO_THUA,TENCHU";
            queryDef.WhereClause = dieukien;
            ICursor cursor = queryDef.Evaluate();

            //queryFilter.WhereClause = dieukien;

            //IQueryFilterDefinition queryFilterDef = (IQueryFilterDefinition)queryFilter;
            //queryFilterDef.PostfixClause = "ORDER BY SO_TO";

            //ICursor cursor = table.Search(queryFilter, false);
            return cursor;
        }
        

        private void showDataThua(int gioihan)
        {
            //string strNameTable="THUA";
            string strNameFields = "SO_THUA,TENCHU";
            string strDieukien = "";
            switch (gioihan)
            {
                case 0:
                    strDieukien="TENCHU='4'";
                    break;
                default:
                    strDieukien = "";
                    break;
            }
            IFeatureClass featureClassThua = FeatureWorkspace.OpenFeatureClass(_strNameTableThua);
            //ITable tblThua = (ITable)featureClassThua;
            ICursor cursor = queryAttribute(_strNameTableThua, strNameFields, strDieukien);
            //IFeature feature = null;
            IRow row = null;
            String[] strRow = new string[cursor.Fields.FieldCount];
            //gan cac cot cua bang truy van vao datagridview thua
            dgvThua.ColumnCount = cursor.Fields.FieldCount;
            for (int i = 0; i < cursor.Fields.FieldCount; i++)
            {
                dgvThua.Columns[i].Name = cursor.Fields.get_Field(i).Name;
            }

            try
            {
                dgvThua.Rows.Clear();
                while ((row = cursor.NextRow()) != null)
                {
                    for (int i = 0; i < cursor.Fields.FieldCount; i++)
                    {
                        strRow[i] = row.get_Value(i).ToString();
                    }
                    dgvThua.Rows.Add(strRow);
                    strRow = new String[cursor.Fields.FieldCount];
                    //row = cursor.NextRow();
                    //MessageBox.Show("doi tuong: " + row.get_Value(1));
                }
            }
            catch (Exception err) { MessageBox.Show(err.ToString()); }
            Marshal.ReleaseComObject(cursor);
        }

        private void tbxXa_TextChanged(object sender, EventArgs e)
        {

        }

        private void tbxXa_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                addDataForCmbXa();
            }
        }

        private void tbxHuyen_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                addDataForCmbHuyen();
            }
        }

        private void cbxTypeCalHuyen_SelectedIndexChanged(object sender, EventArgs e)
        {
            //ten huyen: 1/TX Tây Ninh,2/Tân Biên,3/Tân Châu,4/Dương Minh Châu,5/Châu Thành,6/Hòa Thành,7/Bến Cầu,
            //8/Gò Dầu,9/Trảng Bàng
            string strHuyen = cbxTypeCalHuyen.SelectedItem.ToString();
            cbxTypeCalXa.Items.Clear();
            cbxTypeCalXa.Items.Add("Tất cả các Xã");
            //MessageBox.Show(strHuyen);
            int i=0;
            cbxHuyenView.Items.Clear();
            
            switch (strHuyen)
            {
                case "TX Tây Ninh":
                    for (i = 0; i < _strTenXaTayNinh.Length; i++)
                    {
                        cbxTypeCalXa.Items.Add(_strTenXaTayNinh[i]);
                    }
                    cbxTypeCalXa.Enabled = true;
                    _arrTenXaTemp = _strTenXaTayNinh;
                    break;
                case "Tân Biên":
                    
                    for (i = 0; i < _strTenXaTanBien.Length; i++)
                    {
                        cbxTypeCalXa.Items.Add(_strTenXaTanBien[i]);
                    }
                    cbxTypeCalXa.Enabled = true;
                    _arrTenXaTemp = _strTenXaTanBien;
                    break;
                case "Tân Châu":

                    for (i = 0; i < _strTenXaTanChau.Length; i++)
                    {
                        cbxTypeCalXa.Items.Add(_strTenXaTanChau[i]);
                    }
                    cbxTypeCalXa.Enabled = true;
                    _arrTenXaTemp = _strTenXaTanChau;
                    break;
                case "Dương Minh Châu":

                    for (i = 0; i < _strTenXaDuongMinhChau.Length; i++)
                    {
                        cbxTypeCalXa.Items.Add(_strTenXaDuongMinhChau[i]);
                    }
                    cbxTypeCalXa.Enabled = true;
                    _arrTenXaTemp = _strTenXaDuongMinhChau;
                    break;
                case "Châu Thành":

                    for (i = 0; i < _strTenXaChauThanh.Length; i++)
                    {
                        cbxTypeCalXa.Items.Add(_strTenXaChauThanh[i]);
                    }
                    cbxTypeCalXa.Enabled = true;
                    _arrTenXaTemp = _strTenXaChauThanh;
                    break;
                default:
                    cbxTypeCalXa.Items.Add("Tất cả các xã");
                    cbxTypeCalXa.Enabled = false;
                    cbxHuyenView.Items.Clear();
                    for (i = 0; i < _strTenHuyen.Length; i++)
                    {
                        cbxHuyenView.Items.Add(_strTenHuyen[i]);
                    }
                    _arrTenXaTemp = _strTenXaTayNinh;
                    break;
            }
            if (strHuyen != "Tất cả các Huyện")
            {
                cbxHuyenView.Items.Clear();
                cbxHuyenView.Items.Add(strHuyen);
            }
            cbxHuyenView.SelectedIndex = 0;
            cbxTypeCalXa.SelectedIndex = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string sde = this.SdeEnvironment;//"C:/P2.mdb/P2";
                string outFeature = "e";//StrPathTempFolder + "\\" + StrNameTempMdbFile + ".mdb" + "\\p2_duong_buff_50";
                //MessageBox.Show(outFeature);
                ITnToolsSpatial spatialTool = new TnTools();//TnTools(StrPathTempFolder+"\\"+StrNameTempMdbFile+".mdb");
                ITnToolsWorkspace workspaceTool = new TnTools();
                spatialTool.TnBufferInsideSde("p2_duong", outFeature,10, sde,this.SdeWorkspace);

                IFeatureLayer flIn = new FeatureLayer();
                //IFeatureClass bufferFeatureClass = workspaceTool.OpenFeatureClassFromSDE(this.SdeWorkspace, outFeature);
                flIn.FeatureClass = workspaceTool.OpenFeatureClassFromSDE(this.SdeWorkspace, "p2_thua");
                IFeatureLayer flSelect = new FeatureLayer();
                IFeatureClass fcSelect = workspaceTool.OpenFeatureClassFromSDE(this.SdeWorkspace, "bout_feature");
                flSelect.FeatureClass = fcSelect;
                IFeatureLayer flOut = new FeatureLayer();
                IFeatureClass fcOut = flOut.FeatureClass;
                System.Windows.Forms.Control.ControlCollection controlCol = _tabTayNinh.SelectedTab.Controls;
                DataGridView dtgv = new DataGridView();
                foreach (Control con in controlCol)
                {
                    dtgv = (DataGridView)con;
                }
                spatialTool.TnIntersectSelection("p2_thua", "e", this.SdeEnvironment, this.SdeWorkspace, dtgv);
                //MessageBox.Show(fcOut.AliasName);

                //spatialTool.TnIntersectSelection(
                //Geoprocessor gp = new Geoprocessor();
                ////IDataset dataSet = (IDataset)Workspace;
                
                //string outName="C:\\P2\\hem_copy";
                //gp.SetEnvironmentValue("workspace", sde);
                ////outName = gp.ValidateTableName(outName, "Database Connections/Connection to HT-LAPTOP.sde");
                //ESRI.ArcGIS.AnalysisTools.Buffer bufferTool = new ESRI.ArcGIS.AnalysisTools.Buffer();
                //bufferTool.in_features = "p2_hem";
                
                //bufferTool.out_feature_class =outName;
                ////bufferTool.line_side = side_type;
                ////bufferTool.line_end_type = end_type;
                ////bufferTool.dissolve_option = "NONE";
                //bufferTool.buffer_distance_or_field = 50;
                //gp.Execute(bufferTool, null);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                Geoprocessor gp = new Geoprocessor();
                //string sde = "Database Connections/Connection to HT-LAPTOP.sde";//"C:/P2.mdb/P2";
                string outName = "Database Connections/Connection to HT-LAPTOP.sde/duong_selected";
                //gp.SetEnvironmentValue("workspace", sde);
                //outName = gp.ValidateTableName(outName, sde);
                ESRI.ArcGIS.DataManagementTools.CopyFeatures copyTool = new ESRI.ArcGIS.DataManagementTools.CopyFeatures();
                copyTool.in_features = "Database Connections/Connection to HT-LAPTOP.sde/P2_DUONG";//"C:\\P2.mdb\\duongcopy2";
                copyTool.out_feature_class = outName;
                //copyTool. = "Database Connections/Connection to HT-LAPTOP.sde";
                //copyTool.out_name = "duongcopy";
                //copyTool.config_keyword
                gp.Execute(copyTool, null);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Geoprocessor gp = new Geoprocessor();
            
            gp.SetEnvironmentValue("workspace", @"C:\a");
            IGpEnumList fcs = gp.ListFeatureClasses("*", "", "");

            // Set the workspace to SDE for ValidateTableName.
            gp.ResetEnvironments();
            string wks = "Database Connections/Connection to HT-LAPTOP.sde";
            gp.SetEnvironmentValue("workspace", wks);

            string fc = fcs.Next();
            string outfc = "";
            IVariantArray parameters = new VarArrayClass();
            ESRI.ArcGIS.DataManagementTools.CopyFeatures copyTool = new ESRI.ArcGIS.DataManagementTools.CopyFeatures();
            
            while (fc != "")
            {
                // Validate the output name.
                outfc = gp.ValidateTableName(fc, wks);

                // Copy the features from D:/St_Johns to the SDE workspace.
                copyTool.in_features = fc;
                copyTool.out_feature_class = outfc;
                copyTool.config_keyword = "GEOMETRY";
                //parameters.Add(fc);
                //parameters.Add(outfc);
                //gp.Execute("CopyFeatures_management", parameters, null);
                gp.Execute(copyTool, null);
                fc = fcs.Next();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            
            
            //MessageBox.Show( aoInit.IsProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeEngineGeoDB).ToString());
            IFields fields;
            IFeatureClass featureClass= FeatureWorkspace.OpenFeatureClass("P2_DUONG");
            fields = featureClass.Fields;

            CreateStandaloneFeatureClass(SdeWorkspace, "truonghinh1", fields, "Shape");
        }
        public void CreateStandaloneFeatureClass(IWorkspaceEdit workspace, String
  featureClassName, IFields fieldsCollection, String shapeFieldName)
        {
            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;
            IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc;

            // Use IFieldChecker to create a validated fields collection.
            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null;
            //fieldChecker.ValidateWorkspace = workspace;
            fieldChecker.Validate(fieldsCollection, out enumFieldError, out
    validatedFields);

            // The enumFieldError enumerator can be inspected at this point to determine 
            // which fields were modified during validation.
            try
            {
                // Fetch a license and initialize it
                IAoInitialize aoInit = new AoInitializeClass();
                aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeEngineGeoDB);
                IFeatureClass featureClass = featureWorkspace.CreateFeatureClass
                  (featureClassName, validatedFields, ocDesc.InstanceCLSID,
                  ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, shapeFieldName,
                  "");
            }
            catch (COMException err)
            {
                MessageBox.Show(err.ToString());
            }
            //return featureClass;
        }

        private void FrmCalculateLandPrize_Load(object sender, EventArgs e)
        {
            //initTabControls();
            //If license initialization failed,
            //if (axLicenseControl1.Status != esriLicenseStatus.esriLicenseCheckedOut)
            //{
            //    string failure = "License initialization failed for the following reason:" +
            //        Environment.NewLine + axLicenseControl1.Summary + Environment.NewLine +
            //        Environment.NewLine + "The status" +
            //        "of the requested license(s) is as follows:";

            //    //get the status of the requested licenses.
            //    string[] availability = axLicenseControl1.get_LicenseAvailability
            //        (esriLicenseStatusOptions.esriLicenseStatusRequested).Split
            //        (Environment.NewLine.ToCharArray());
            //    for (int i = 0; i <= availability.Length - 1; i++)
            //    {
            //        failure = failure + Environment.NewLine + availability[i];
            //    }

            //    //Report failure to user.
            //    System.Windows.Forms.MessageBox.Show(failure, "LicenseControl",
            //        MessageBoxButtons.OK);

                //Programmatically shut down the application...
            //}


        }

        private void button5_Click(object sender, EventArgs e)
        {
            //DataGrid newdatagrid = new DataGrid();
            
            //TabPage newtab = new TabPage("newtab");
            //tctDataView.TabPages.Add(newtab);
            //newtab.Controls.Add(newdatagrid);
            //newdatagrid.Dock = DockStyle.Fill;
            ////newdatagrid.
            //newdatagrid.Height = 100;
            TnUtilities uti = new TnUtilities();
            
            //this.splitContainer1.Panel2.Controls.Remove(tctDataView);
            //tctDataView.Visible = false;
            //this.splitContainer1.Panel2.Controls.Add(_tabTayNinh);
            //uti.TnAddTabpageWithDatagridview(tctDataView, "newTab", tabPage1.Width, tabPage1.Height, "newGrid", dgvThua.Width, dgvThua.Height);
        }
        private void initTabControls()
        {
            TnUtilities utility = new TnUtilities();
            #region tabControl Tay Ninh
            _tabTayNinh = utility.TnCreateTabControl("tctTayNinh", tctDataView.Location.X, tctDataView.Location.Y, tctDataView.Width, tctDataView.Height,100);
            _tabTayNinh.TabPages.Clear();
            //utility.TnAddTabpageWithDatagridview(_tabTayNinh,"tabTxTayNinh" ,"TX Tây Ninh", tabPage1.Width, tabPage1.Height,"dgvTayNinh",dgvThua.Width,dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTayNinh, "tabPhuong1", "Phường 1", tabPage1.Width, tabPage1.Height, "dgvPhuong1", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTayNinh, "tabPhuong2", "Phường 2", tabPage1.Width, tabPage1.Height, "dgvPhuong2", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTayNinh, "tabPhuong3", "Phường 3", tabPage1.Width, tabPage1.Height, "dgvPhuong3", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTayNinh, "tabPhuong4", "Phường 4", tabPage1.Width, tabPage1.Height, "dgvPhuong4", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTayNinh, "tabHiepNinh", "Hiệp Ninh", tabPage1.Width, tabPage1.Height, "dgvHiepNinh", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTayNinh, "tabThanhTan", "Thạnh Tân", tabPage1.Width, tabPage1.Height, "dgvThanhTan", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTayNinh, "tabTanBinh", "Tân Bình", tabPage1.Width, tabPage1.Height, "dgvTanBinh", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTayNinh, "tabNinhSon", "NinhSon", tabPage1.Width, tabPage1.Height, "dgvNinhSon", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTayNinh, "tabBinhMinh", "Bình Minh", tabPage1.Width, tabPage1.Height, "dgvBinhMinh", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTayNinh, "tabNinhThanh", "Ninh Thạnh", tabPage1.Width, tabPage1.Height, "dgvNinhThanh", dgvThua.Width, dgvThua.Height);
            
            
            //tctDataView.Visible = true;
            this._tabTayNinh.Visible = true;
            //MessageBox.Show(tctDataView.Width.ToString()+"__"+this._tabTayNinh.Visible.ToString()+"__"+_tabTayNinh.Location.X.ToString()+"__"+_tabTayNinh.Width.ToString());
            #endregion

            #region tabControl Tan Bien
            _tabTanBien = utility.TnCreateTabControl("tctTanBien",tctDataView.Location.X,tctDataView.Location.Y, tctDataView.Width, tctDataView.Height,tctDataView.TabIndex);
            _tabTanBien.TabPages.Clear();
            utility.TnAddTabpageWithDatagridview(_tabTanBien, "tabTtTanBien", "TT Tân Biên", tabPage1.Width, tabPage1.Height, "dgvTanBien", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTanBien, "tabTanLap", "Tân Lập", tabPage1.Width, tabPage1.Height, "dgvTanLap", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTanBien, "tabThanhTay", "Thạnh Tây", tabPage1.Width, tabPage1.Height, "dgvThanhTay", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTanBien, "tabTraVong", "Trà Vong", tabPage1.Width, tabPage1.Height, "dgvTraVong", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTanBien, "tabMoCong", "Mỏ Công", tabPage1.Width, tabPage1.Height, "dgvMoCong", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTanBien, "tabTanPhong", "Tân Phong", tabPage1.Width, tabPage1.Height, "dgvTanPhong", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTanBien, "tabThanhBinh", "Thạnh Bình", tabPage1.Width, tabPage1.Height, "dgvThanhBinh", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTanBien, "tabTanBinh", "Tân Bình", tabPage1.Width, tabPage1.Height, "dgvTanBinh", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTanBien, "tabHoaHiep", "Hòa Hiệp", tabPage1.Width, tabPage1.Height, "dgvHoaHiep", dgvThua.Width, dgvThua.Height);
            utility.TnAddTabpageWithDatagridview(_tabTanBien, "tabThanhBac", "Thạnh Bắc", tabPage1.Width, tabPage1.Height, "dgvThanhBac", dgvThua.Width, dgvThua.Height);
            #endregion

            _tabControlList.Add(tctDataView);
            _tabControlList.Add(_tabTayNinh);
            _tabControlList.Add(_tabTanBien);

            addAllOnPanel2(this.splitContainer1.Panel2, _tabControlList);
            offAllOnOne(_tabControlList, tctDataView);
            foreach (TabControl tab in _tabControlList)
            {
                tab.SelectedIndexChanged += new System.EventHandler(tab_select);
            }
            
        }
        private void tab_select(object sender, EventArgs e)
        {
            TabControl tab = (TabControl)sender;
            TnTabPage tabpage=(TnTabPage) tab.SelectedTab;
            
            ITnToolsTable toolTable = new TnTools();
            DataGridView dtgv = new DataGridView();
            foreach (Control con in tab.Controls)
            {
                if (con.GetType() == typeof(DataGridView))
                {
                    dtgv = (DataGridView)con;
                }
            }
            if (!tabpage.IsSelected)
            {
                //toolTable.TnShowDataUseSQL(this._strServer, this._strDatabase, this._strUser, this._strPass, "tn_thua", "", 1);
                this.bwShowData.RunWorkerAsync();
                //MessageBox.Show(tab.SelectedTab.Text);
            }
            tabpage.IsSelected = true;
            strCurrentSelectedTabPageName = tab.SelectedTab.Text;
        }

        private void cbxHuyenView_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbxHuyenView.Text)
            {
                case "TX Tây Ninh":
                    offAllOnOne(_tabControlList,_tabTayNinh);
                    //MessageBox.Show(_tabTayNinh.Visible.ToString());
                    _arrTenXaTemp = _strTenXaTayNinh;
                    currentSelectedTabControl = _tabTayNinh;
                    break;
                case "Tân Biên":
                    offAllOnOne(_tabControlList,_tabTanBien);
                    _arrTenXaTemp = _strTenXaTayNinh;
                    currentSelectedTabControl = _tabTanBien;
                    break;
                default:
                    offAllOnOne(_tabControlList,tctDataView);
                    _arrTenXaTemp = _strTenXaTayNinh;
                    currentSelectedTabControl = _tabTayNinh;
                    break;
            }

        }
        private void offAllOnOne(List<TabControl> listControl, TabControl ControlOn)
        {
            
            foreach(TabControl control in listControl)
            {
                control.Visible = false;
            }
            if (ControlOn != null)
            {
                ControlOn.Visible = true;
            }
        }
        private void addAllOnPanel2(SplitterPanel panel, List<TabControl> listControl)
        {
            foreach (TabControl control in listControl)
            {
                panel.Controls.Add(control);
            }
        }

        private void cbxTypeCalXa_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbxTypeCalXa.Text != "Tất cả các Xã")
            {
                switch (cbxTypeCalHuyen.Text)
                {
                    case "TX Tây Ninh":
                        _tabTayNinh.SelectedIndex=cbxTypeCalXa.SelectedIndex-1;
                        break;
                    case "Tân Biên":
                        _tabTanBien.SelectedIndex=cbxTypeCalXa.SelectedIndex-1;
                        break;
                    default :
                        break;
                }
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 1: Make feature layers using the MakeFeatureLayer tool for the inputs to the SelectByLocation tool.
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////

            // Intialize the Geoprocessor 
            Geoprocessor GP = new Geoprocessor();

            // Intialize the MakeFeatureLayer tool
            MakeFeatureLayer makefeaturelayer = new MakeFeatureLayer();
            makefeaturelayer.in_features = @"C:\tayninh\temp\tempmdb.mdb\p2_duong_buff_50";
            makefeaturelayer.out_layer = "gt_buff_lyr";
            RunTool(GP, makefeaturelayer, null);
            //GP.SetEnvironmentValue("workspace","Database Connections/Connection to ht_laptop.sde");
            GP.ResetEnvironments();
            makefeaturelayer.in_features = "Database Connections/Connection to HT-LAPTOP.sde/P2_THUA";//@"C:\tayninh\temp\tempmdb.mdb\p2_thua";
            makefeaturelayer.out_layer = "p2_sde_thua_lyr";
            RunTool(GP, makefeaturelayer, null);
            GP.ResetEnvironments();
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 2: Execute SelectLayerByLocation using the feature layers to select all wells that intersect theb bedrock geololgy.
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            // Intialize the SelectLayerByLocation tool
            SelectLayerByLocation SelectByLocation = new SelectLayerByLocation();

            SelectByLocation.in_layer = "p2_sde_thua_lyr";
            SelectByLocation.select_features = "gt_buff_lyr";
            SelectByLocation.overlap_type = "INTERSECT";

            ILayerFile lf = new LayerFileClass();
            

            IFeatureClass fc;
            //fc.
            IQueryFilter qf;
            //IGeoProcessorResult result = (IGeoProcessorResult)GP.Execute(SelectByLocation, null);
            IGPUtilities gpu = new GPUtilitiesClass();
            //gpu.DecodeFeatureLayer(result.GetOutput(0), out fc, out qf);
            RunTool(GP, SelectByLocation, null);
            try
            {
                ISpatialFilter spatialFilter = new SpatialFilterClass();
                //spatialFilter.
                //IQueryFilter queryFilter=
                IFeatureSelection fs;
                //fs = (IFeatureSelection)l;
                IFeatureLayerDefinition fld = new FeatureLayerClass();
                //ISelectionSet selectionSet = fs.SelectionSet;
                IFeatureLayer featureLayer;
                IFeatureClass featureClass2;
                
                featureLayer = fld.CreateSelectionLayer("newname", true, null, "");

                featureClass2 = featureLayer.FeatureClass;

                ITable table3 = (ITable)featureClass2;
                MessageBox.Show(table3.RowCount(null).ToString());
            }
            catch (Exception err) { MessageBox.Show(err.ToString()); }
            /////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 3: Execute SelectLayerByAttribute to select all wells that have a well yield > 150 L/min.
            /////////////////////////////////////////////////////////////////////////////////////////////////

            // Intialize the SelectLayerByAttribute tool
            SelectLayerByAttribute SelectByAttribute = new SelectLayerByAttribute();
            IRow r;
            ITableSelection t;
            
            
            //SelectByAttribute.in_layer_or_view = "p2_thua_lyr";
            //SelectByAttribute.selection_type = "NEW_SELECTION";
            //SelectByAttribute.where_clause = "";
            //RunTool(GP, SelectByAttribute, null);

            SaveToLayerFile saveLayer = new SaveToLayerFile();
            saveLayer.in_layer = "p2_sde_thua_lyr";
            saveLayer.out_layer = @"C:\tayninh\temp\p2_sde_thua_lyr_save2.lyr";
            
            RunTool(GP, saveLayer, null);
            ////////////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 4: Execute CopyFeatures tool to create a new feature class of wells with well yield > 150 L/min.
            ////////////////////////////////////////////////////////////////////////////////////////////////////////

            // Intialize the CopyFeatures tool
            CopyFeatures CopyFeatures = new CopyFeatures();

            //CopyFeatures.in_features = fc;
            //CopyFeatures.out_feature_class = @"C:\tayninh\temp\tempmdb.mdb\p2_thua_lyr_d";

            // Set the output Coordinate System environment
            //GP.SetEnvironmentValue("outputCoordinateSystem",
                //@"C:\Program Files\ArcGIS\Coordinate Systems\Projected Coordinate Systems\UTM\Nad 1983\NAD 1983 UTM Zone 21N.prj");

            //RunTool(GP, CopyFeatures, null);
            IFeatureLayer l = new FeatureLayerClass();
            IFeatureClass a;
            ILayerFile b = new LayerFileClass();
            b.Open(@"C:\tayninh\temp\p2_sde_thua_lyr_save2.lyr");
            l = (IFeatureLayer)b.Layer;
            a = l.FeatureClass;
            
            
            ITable table2=(ITable)a;
            
            
            
            //MessageBox.Show(fs.SelectionSet.Count.ToString());
            IQueryDef qd=FeatureWorkspace.CreateQueryDef();
            qd.Tables="p2_thua,C:\\tayninh\\temp\\tempmdb.mdb\\p2_thua_lyr_c";
            //qd.Tables="
            
            CalculateField cal = new CalculateField();
            
            cal.in_table = table2;
            cal.field = "GHI_CHU";
            cal.expression = "\"hi\"";
            RecordSet re = new RecordSet();
            
            GP.ResetEnvironments();
            try
            {
                RunTool(GP, cal, null);
                //MessageBox.Show(l.DataSourceType);
                MessageBox.Show(GP.GetMessage(2));
            }
            catch (Exception err) { MessageBox.Show(err.ToString()); }
        }
        private static void RunTool(Geoprocessor geoprocessor, IGPProcess process, ITrackCancel TC)
        {

            // Set the overwrite output option to true
            geoprocessor.OverwriteOutput = true;

            // Execute the tool            
            try
            {
                geoprocessor.Execute(process, null);
                ReturnMessages(geoprocessor);

            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                ReturnMessages(geoprocessor);
            }
        }
        private static void ReturnMessages(Geoprocessor gp)
        {
            if (gp.MessageCount > 0)
            {
                for (int Count = 0; Count <= gp.MessageCount - 1; Count++)
                {
                    Console.WriteLine(gp.GetMessage(Count));
                    //MessageBox.Show(gp.GetMessage(Count));
                }
            }

        }

        private void button7_Click(object sender, EventArgs e)
        {
            try
            {
                //Geoprocessor GP = new Geoprocessor();
                IFeatureCursor featureCursor;
                IFeatureClass featureClass;
                IFeature feature;
                IFeatureClass thua;
                IGeometryCollection geometryCollection=new GeometryBagClass();
                ITnToolsWorkspace toolWorkspace=new TnTools();
                featureClass = toolWorkspace.OpenFeatureClassFromSDE(SdeWorkspace,"aout_feature");
                thua = toolWorkspace.OpenFeatureClassFromSDE(SdeWorkspace,"p2_thua");
                featureCursor = featureClass.Search(null, true);
                object obj = Type.Missing;
                feature = featureCursor.NextFeature();
                while (feature != null)
                {
                    geometryCollection.AddGeometry(feature.Shape,ref obj,ref obj);
                    feature = featureCursor.NextFeature();
                }

                SpatialFilter spatialFilter = new SpatialFilter();
                spatialFilter.Geometry = geometryCollection.get_Geometry(1);
                spatialFilter.GeometryField = thua.ShapeFieldName;
                spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                
                IFeatureSelection featureSelection;
                IFeatureLayer thuaLayer = new FeatureLayerClass();
                
                thuaLayer.FeatureClass = thua;
                
                IQueryFilter qf = spatialFilter;
                //ISelectionSet selectionSet;
                
                IFeatureLayerDefinition flDef = (IFeatureLayerDefinition)thuaLayer;
                //flDef.DefinitionExpression = "SO_TO ='3.0'";
                featureSelection = (IFeatureSelection)thuaLayer;
                featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                
                //selectionSet = thua.Select(spatialFilter, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionNormal, null);
                
                
                IFeatureLayer selectLayer = flDef.CreateSelectionLayer("newlayer", true, null, null);
                IFeatureClass selectClass = selectLayer.FeatureClass;
                IFeatureCursor fCursor = selectLayer.Search(null,false);
                IFeature ft = fCursor.NextFeature();
                int a = 0;
                while (ft != null)
                {
                    a = a + 1;
                    // ft.Fields.get_Field(ft.Fields.FindFieldByAliasName("GHI_CHU"));
                    //MessageBox.Show(ft.Fields.get_Field(ft.Fields.FindFieldByAliasName("GHI_CHU")).Editable.ToString());
                    ft.set_Value(ft.Fields.FindFieldByAliasName("GHI_CHU"),"inter");
                    //fCursor.UpdateFeature(ft);
                    ft.Store();
                    //MessageBox.Show(ft.get_Value(ft.Fields.FindFieldByAliasName("GHI_CHU")).ToString());
                    ft = fCursor.NextFeature();
                    
                }
                
                MessageBox.Show(a.ToString());
                
                ITable table = (ITable)selectClass;
                
            }
            catch (Exception err) { MessageBox.Show(err.ToString()); }
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void dgvThua_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show();
        }

        private void dgvThua_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //e.
            DataGridView datag = (DataGridView)sender;
            //MessageBox.Show (datag.Rows[e.RowIndex].Cells[0].Value.ToString());
        }

        private void button8_Click(object sender, EventArgs e)
        {
            this.bwShowData.RunWorkerAsync();
        }

        private void bwShowTable_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            //int arg = (int)e.Argument;
            //System.Windows.Forms.Control.ControlCollection controlCol = _tabTayNinh.SelectedTab.Controls;
            //DataGridView dtgv = new DataGridView();
            //foreach (Control con in controlCol)
            //{
            //    dtgv = (DataGridView)con;
            //}

            e.Result = showDataBackGround(bw);
        }
        private List<string[]> showDataBackGround(BackgroundWorker bw)
        {
            int result = 0;
            List<string[]> listVal=new List<string[]>();
            string[] fields;
            if (!bw.CancellationPending)
            {
                ITnToolsTable toolTable = new TnTools();
                
                
                //listVal=toolTable.TnShowDataUseSQL(this._strServer,this._strDatabase, this._strUser, this._strPass, "tn_thua", "", 1);
                //MessageBox.Show(this._sqlConnection.ToString());
                listVal = toolTable.TnShowDataUseSQL(this._sqlConnection, "tn_thua", out fields, "", 1);
                listVal.Add(fields);
            }
            
            return listVal;
        }

        private void button9_Click(object sender, EventArgs e)
        {
            this.bwShowData.CancelAsync();
        }

        private void bwShowTable_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            int intNumRows = 0;
            int intNumCols=0;
            System.Windows.Forms.Control.ControlCollection controlCol = currentSelectedTabControl.SelectedTab.Controls;
            DataGridView dtgv = new DataGridView();
            foreach (Control con in controlCol)
            {
                dtgv = (DataGridView)con;
            }
            List<string[]> listVal=(List<string[]>)e.Result;
            string[] strRow=listVal[0];
            
            intNumCols=strRow.Length;
            dtgv.ColumnCount = intNumCols;
            dtgv.Rows.Clear();
            intNumRows = listVal.Count;

            string[] strCols=listVal[intNumRows-1];
            //MessageBox.Show(listVal.Count.ToString());
            for (int i = 0; i < intNumCols; i++)
            {
                dtgv.Columns[i].Name = strCols[i];
            }
            
            for (int i = 0; i < intNumRows - 1; i++)
            {
                dtgv.Rows.Add(listVal[i]);
            }
            
            //foreach (string[] row in listVal)
            //{
            //    dtgv.Rows.Add(row);
            //}
        }
        //tinh gia dat
        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            bw.WorkerReportsProgress = true;
            e.Result = ExcuteCalculating(bw);
            
            //bw.ReportProgress(50);
            
        }
        private IFeatureLayer ExcuteCalculating(BackgroundWorker bw)
        {
            
            ITnToolsSpatial toolSpatial = new TnTools();
            ITnToolsTable toolTable = new TnTools();
            ITnToolsCalculator toolCal = new TnTools();
            IFeatureLayer fl = new FeatureLayerClass();
            toolTable.TnFormatTable(SdeWorkspace, _strNameTableThua, _strNameTableDuong, _strNameTableHem);
            try
            {
                IFeatureClass fc = FeatureWorkspace.OpenFeatureClass("tn_duong_buff_05");
            }
            catch
            {
                toolSpatial.TnBufferInsideSde(_strNameTableDuong, "tn_duong_buff_05", 0.5, SdeEnvironment, SdeWorkspace);
            }
            try
            {
                IFeatureClass fc = FeatureWorkspace.OpenFeatureClass("tn_duong_buff_50");
            }
            catch
            {
                toolSpatial.TnBufferInsideSde(_strNameTableDuong, "tn_duong_buff_50", 50, SdeEnvironment, SdeWorkspace);
            }
            bw.ReportProgress(50);

            fl = toolCal.TnTinhThuaMattien(_strNameTableThua, "tn_duong_buff_05", SdeWorkspace);
            bw.ReportProgress(100);
            return fl;
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("ok");
        }

        private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
            this.label1.Text = e.ProgressPercentage.ToString();
        }

        private void button10_Click(object sender, EventArgs e)
        {
            backgroundWorker3.RunWorkerAsync();
        }
        private void excuteButton10(BackgroundWorker bw)
        {
            ITnToolsWorkspace toolWorkspace = new TnTools();
            ITnToolsSpatialRel toolSpatialRel = new TnTools();

            IFeatureClass duong = toolWorkspace.OpenFeatureClassFromSDE(this.SdeWorkspace, "tn_duong_buff_05");
            IFeatureClass thua = toolWorkspace.OpenFeatureClassFromSDE(this.SdeWorkspace, "tn_thua");
            // layer chua cac doi tuong duoc select
            IFeatureSelection featureSelection; ;

            IFeatureCursor duongCursor = duong.Search(null, true);
            IFeature duongFeature = duongCursor.NextFeature();

            IFeatureLayer selectedLayer; ;

            int numSelectedFeature = toolSpatialRel.TnIntersection(ref thua, ref duongFeature, out selectedLayer, out featureSelection, esriSelectionResultEnum.esriSelectionResultNew);
            //MessageBox.Show(numSelectedFeature.ToString());
            //selectedLayer = flDef.CreateSelectionLayer("layer2", true, null, null);
            
            //IFeatureClass selectedClass = selectedLayer.FeatureClass;
            IQueryFilter qrf = new QueryFilterClass();
            ICursor selectedCu=null;
            qrf.SubFields = "*";
            qrf.WhereClause = "OBJECTID>0";
            featureSelection.SelectionSet.Search(qrf,false,out selectedCu);
            IRow row=selectedCu.NextRow();
            int a = 0;
            string k = "hihi";
            while (row != null)
            {
                a++;
                row.set_Value(row.Fields.FindField("ghichu"), string.Format("{0}",k));
                row.Store();
                row = selectedCu.NextRow();
            }
            
            try
            {
                //selectedFeature = selectedCursor.NextFeature();
                //while (selectedFeature != null)
                //{
                //    a = a + 1;
                //    MessageBox.Show(a.ToString());
                //    selectedFeature = selectedCursor.NextFeature();
                //}
                //for (int i = 0; i < featureSelection.SelectionSet.Count; i++)
                //{
                //    MessageBox.Show(selectedFeature.get_Value(0).ToString());
                //    selectedFeature.set_Value(selectedFeature.Fields.FindField("ghichu"), "intersect");
                //    selectedFeature.Store();
                //    selectedFeature = selectedCursor.NextFeature();
                //}
            }
            catch { MessageBox.Show("no feature"); }
            MessageBox.Show("numSelected= " + numSelectedFeature.ToString() + "___ a= " + a.ToString()+"___selectionset= "+featureSelection.SelectionSet.Count.ToString());
        }

        private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            bw.WorkerReportsProgress = true;
            excuteButton10(bw);
        }
        private void addButton()
        {
            Button button=new Button();
            button.Name = "button11";
            button.Size = new System.Drawing.Size(75, 23);
            button.TabIndex = 28;
            button.Text = "button11";
            button.UseVisualStyleBackColor = true;
            this.comboBox1.Items.Add(button);
        }
        TnThua thua = null;
        TnDuong duong = null;
        TnDuong duong50 = null;
        TnDuong duong05 = null;
        private void sbtn_Click(object sender, EventArgs e)
        {
            calcFactory = TnCalculatorFactory.CallMe;// new TnCalculatorFactory(RootForm._sdeWorkspace, RootForm._sdeEnvironment, RootForm._arrUserInfo);
            calcFactory.SetParams(RootForm.SdeWorkspace, RootForm.SdeEnvironment, RootForm.UserInfo);
            if (!sbtnCalculate.pos())
            {
                if (sbtnCalculate.Text == "Tính lại toàn bộ")
                {
                    //MessageBox.Show(sbtnCalculate.Text);
                    bwCalculateAll.RunWorkerAsync();
                }
                else
                {
                    ITnToolsWorkspace toolWsp = new TnTools();
                    ITnToolsTable toolTbl = new TnTools();
                    toolTbl.TnFormatTable(this._sdeWorkspace, "tn_thua");
                    //MessageBox.Show("ok");
                    TnThuaFactory thuaFactory = new TnThuaFactory();
                    TnDuongFactory duongFactory = new TnDuongFactory();
                    thua = thuaFactory.GetThua("3010", this._sdeWorkspace);
                    //duong = duongFactory.GetDuong(EnumLoaiDuong.dp_loai1, this._sdeWorkspace);
                    duong50 = duongFactory.GetDuong(EnumLoaiDuong.dp_loai1_buff_50, this._sdeWorkspace);
                    
                    duong05 = duongFactory.GetDuong(EnumLoaiDuong.dp_loai1_buff_05, this._sdeWorkspace);
                    //them cong cu truy van khong gian
                    //TnExToolsFactory toolFact = new TnExToolsFactory();
                    //TnExtensionTools exTool = toolFact.GetExTool(EnumExTools.spatialRelTool);
                    //calcTool.AddExTool(exTool);
                    //exTool = toolFact.GetExTool(EnumExTools.dataManager);
                    //calcTool.AddExTool(exTool);
                    //exTool = toolFact.GetExTool(EnumExTools.spatialTool);
                    //calcTool.AddExTool(exTool);
                    

                    //MessageBox.Show(duong.FeatureClass.AliasName);
                    //TnThua thua = thuaFactory.GetThua("3010", thuafc);
                    //chon mode tinh thua 3010
                    calcTool = calcFactory.GetCalculator(EnumModeCalc.mode3010);
                    calcTool.AddExTool(EnumExTools.spatialRelTool);
                    calcTool.ClearInputValues();
                    calcTool.SetInputValues(ref thua, ref duong05, EnumTask.addInfo3010);
                    calcTool.SetInputValues(ref thua, ref duong50, EnumTask.landPrice3010);
                    calcTool.AddTask(EnumTask.addInfo3010);
                    calcTool.AddTask(EnumTask.landPrice3010);
                    calcTool.BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
                    calcTool.BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted1);
                    calcTool.Start();

                    
                    
                    //calcTool.BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted);
                    //them 2 tham so dau vao cho phep tinh
                    //calcTool.SetInputValues(ref thua,ref duong);
                   

                    //calcTool.SetInputValues(ref thua, ref duong05, EnumTask.addInfo3010);
                    //calcTool.SetInputValues(ref thua, ref duong50, EnumTask.landPrice3010);
                    
                    
                    //thiet lap cac tac vu
                    //((TnCalcThua3010)calcTool).AddTask(EnumTask.addInfo3010);
                    //((TnCalcThua3010)calcTool).AddTask(EnumTask.locthuaExtra);
                    //calcTool.Memory4Calc.curWhereClause = "sothua='1' and ";
                    //calcTool.AddTask(EnumTask.addInfo3010);
                    
                    //calcTool.RemoveTask(EnumTask.addInfo3010);
                    //calcTool.AddTask(EnumTask.landPrice3010);
                   
                    //string[] a = calcTool.ListTasks();
                    ////thiet lap danh sach cac gia tri se duoc luu
                    //List<string[]> param = new List<string[]>();
                    //param.Add(new string[] { "kdat", "3010" });
                    ////param.Add(new string[] { "ghichu", "aa" });
                    //calcTool.Save.listNeedSaved = param;
                    //bat dau tinh
                    
                   
                    //calcTool.BackgroundWorker = this.bwCalculating;
                    //bwCalculating.RunWorkerAsync();
                }
                //MessageBox.Show("hi");
            }
        }

        void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("finished");
        }
        void BackgroundWorker_RunWorkerCompleted1(object sender, RunWorkerCompletedEventArgs e)
        {
            calcTool = calcFactory.GetCalculator(EnumModeCalc.mode3020);
            //MessageBox.Show(calcTool.Name);
            calcTool.AddExTool(EnumExTools.dataManager, EnumExTools.spatialRelTool, EnumExTools.spatialTool);
            calcTool.BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
            calcTool.BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted);
            //thua.FeatureCursor = thua.FeatureClass.Search(null, false);
            duong50.FeatureCursor = duong50.FeatureClass.Search(null, false);
            duong50.Feature = duong50.FeatureCursor.NextFeature();
            calcTool.ClearInputValues();
            calcTool.SetInputValues(ref thua, ref duong50, EnumTask.landPrice3020);
            calcTool.AddTask(EnumTask.landPrice3020);
            string[] a = calcTool.ListTasks();
            //MessageBox.Show(a.Length.ToString()+","+a[0]+","+a[1]);
            calcTool.Start();
            
        }
        void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
            this.label1.Text = e.ProgressPercentage.ToString()+"%";
        }

        private void splitContainer1_Panel2_Click(object sender, EventArgs e)
        {
            this.lblCachTinhTemp.Focus();
            
        }

        private void bwCalculateAll_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            bw.WorkerReportsProgress = true;
            
            if (bwCalculateAll.CancellationPending)
            {
                e.Cancel = true;
                //MessageBox.Show("stop");
                return;
            }
            else
            {
                calculateAll(bw);
            }


        }
        private void calculateAll(BackgroundWorker bw)
        {
            ITnToolsCalculator toolCalculator = new TnTools();
            MessageBox.Show(this.SdeEnvironment);
            toolCalculator.TnCalculateAll("","tn_thua", "tn_duong", "tn_duong_buff_05", "tn_duong_buff_50", "tn_duong_buff_100", "tn_duong_buff_200", this.arrUserInfo,this.SdeEnvironment, this.SdeWorkspace, bw);
        }

        private void bwCalculateAll_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
            this.label1.Text = e.ProgressPercentage.ToString()+"%";
            this.Cursor = Cursors.AppStarting;
            this.pbxWaiting1.Visible = true;
        }

        private void bwCalculateAll_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //MessageBox.Show("ok");
            this.Cursor = Cursors.Arrow;
            this.pbxWaiting1.Visible = false;
        }

        private void btnStopCal_Click(object sender, EventArgs e)
        {
            if (bwCalculateAll.WorkerSupportsCancellation)
            {
                this.bwCalculateAll.CancelAsync();
            }
        }

        private void FrmCalculateLandPrize_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            isShown = false;
            this.Hide();
        }
        //static int global=0;
        private void button12_Click(object sender, EventArgs e)
        {
            //global = global + 1;
            ITnToolsWorkspace toolws=new TnTools();
            
            
            TnThua t;
            TnThua t2;
            TnThuaFactory tf=new TnThuaFactory();
            TnCalculatorFactory calcF = TnCalculatorFactory.CallMe;//(this._sdeWorkspace,this._sdeEnvironment);
            TnToolsCalculator cal;
            //ITnExToolsSpatialRel exT=new TnExtensionTools();
            cal=calcF.GetCalculator(EnumModeCalc.mode3010);
            t=tf.GetThua("3010",this._sdeWorkspace);
            t2=tf.GetThua("3020",this._sdeWorkspace);
            //cal.AddExTool((ITnExTools)exT);
            //MessageBox.Show(t.StrKDat + "---" + t2.StrKDat);
            
        }

        private void bwCalculating_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
        }

        private void bwCalculating_DoWork(object sender, DoWorkEventArgs e)
        {
            if (calcTool.GetType() == typeof(TnCalcThua3010))
            {
                ((TnCalcThua3010)calcTool).testBW(bwCalculating);
            }
            
        }
    }
}
